﻿using System.Collections;
using UnityEngine;



/// <summary>
/// 
/// </summary>
public class ManagedCoroutine
{
    public State CurrentState { get; private set; } = State.Running;
    public IEnumerator Enumerator { get; private set; }
    public Coroutine UnityCoroutine { get; private set; }



    public ManagedCoroutine(IEnumerator enumerator)
    {
        Enumerator = enumerator;
    }


    public void Start(MonoBehaviour owner)
    {
        if (CurrentState == State.Running)
            return;

        CurrentState = State.Running;
        UnityCoroutine = owner.StartCoroutine(Run());
    }

    public void Pause()
    {
        if (CurrentState == State.Running)
            CurrentState = State.Paused;
    }

    public void Resume()
    {
        if (CurrentState == State.Paused)
            CurrentState = State.Running;
    }

    public void Stop()
    {
        if (CurrentState == State.Stopped)
            return;

        CurrentState = State.Stopped;
        //if (UnityCoroutine != null)
        //    CoroutineManager.Instance.StopManagedCoroutine(this);
    }



    private IEnumerator Run()
    {
        while (CurrentState != State.Stopped)
        {
            if (CurrentState == State.Running)
            {
                if (Enumerator.MoveNext())
                    yield return Enumerator.Current;
                else
                    break;
            }
            else
            {
                yield return null;
            }
        }

        CurrentState = State.Stopped;
        //CoroutineManager.Instance.ReturnToPool(this);
    }
}